package com.cskaoyan.service.wx.impl;


import com.cskaoyan.bean.bo.wxcouponbo.WxCouponBo;
import com.cskaoyan.bean.bo.wxcouponbo.WxCouponListBo;
import com.cskaoyan.bean.po.*;
import com.cskaoyan.mapper.MarketCartMapper;
import com.cskaoyan.mapper.MarketCouponMapper;
import com.cskaoyan.mapper.MarketCouponUserMapper;
import com.cskaoyan.service.wx.WxCouponService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @BelongsProject: market-project
 * @BelongsPackage: com.cskaoyan.service.wx.impl
 * @CreateTime: 2022-11-22  14:06
 * @Description: TODO
 * @Version: 1.0
 */
@Service
public class WxCouponServiceImpl implements WxCouponService {
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;
    @Autowired
    MarketCartMapper marketCartMapper;

    /*
    @Override
    public PageInfo<WxCouponListBo> select(Short status, Integer page, Integer limit) {

        Subject subject = SecurityUtils.getSubject();
        // 获取 登录用户信息
        MarketUser primaryPrincipal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        Integer id = primaryPrincipal.getId();

        PageHelper.startPage(page, limit);

        MarketCouponUserExample example = new MarketCouponUserExample();
        MarketCouponUserExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(id);
        List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(example);
        List<WxCouponListBo> list = new ArrayList<>();


        // todo 应该是marketCoupon 而不是MarketCouponUser
        for (MarketCouponUser marketCouponUser : marketCouponUsers) {
            WxCouponListBo wxCouponListBo = new WxCouponListBo();
            Integer couponId = marketCouponUser.getCouponId();
            MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(couponId);

            if (!status.equals(marketCouponUser.getStatus())) {
                continue;
            }

            wxCouponListBo.setCid(couponId);
            wxCouponListBo.setTag(marketCoupon.getTag());
            wxCouponListBo.setDesc(marketCoupon.getDesc());
            wxCouponListBo.setId(marketCouponUser.getId());
            wxCouponListBo.setDiscount(marketCoupon.getDiscount());
            wxCouponListBo.setName(marketCoupon.getName());
            wxCouponListBo.setMin(marketCoupon.getMin());

            if (marketCoupon.getStartTime() == null) {
                //当starttime为空时，说明开始时间为领取的时间，结束时间为领取时间加上有效期天数
                Date addTime = marketCoupon.getAddTime();
                wxCouponListBo.setStartTime(addTime);
                Calendar ca = Calendar.getInstance();
                ca.setTime(addTime);
                ca.add(Calendar.DATE, 10);
                Date endTime = ca.getTime();
                wxCouponListBo.setEndTime(endTime);
            } else {
                wxCouponListBo.setEndTime(marketCoupon.getEndTime());
                wxCouponListBo.setStartTime(marketCoupon.getStartTime());
            }
            Boolean available = ifInDateOrOut(wxCouponListBo.getStartTime(), wxCouponListBo.getEndTime());
            wxCouponListBo.setAvailable(available);
            list.add(wxCouponListBo);
        }
        return new PageInfo<>(list);
    }*/

    @Override
    public PageInfo<WxCouponListBo> select(Short status, Integer page, Integer limit) {

        Subject subject = SecurityUtils.getSubject();
        // 获取 登录用户信息
        MarketUser primaryPrincipal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        Integer id = primaryPrincipal.getId();

        List<WxCouponListBo> list = new ArrayList<>();
        PageHelper.startPage(page, limit);

        MarketCouponUserExample example1 = new MarketCouponUserExample();
        MarketCouponUserExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andUserIdEqualTo(id);
        criteria1.andStatusEqualTo(status);

        List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(example1);
        for (MarketCouponUser marketCouponUser : marketCouponUsers) {
            WxCouponListBo wxCouponListBo = new WxCouponListBo();
            Integer couponId = marketCouponUser.getCouponId();
            MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(couponId);


            wxCouponListBo.setCid(couponId);
            try {
                wxCouponListBo.setTag(marketCoupon.getTag());
                wxCouponListBo.setDesc(marketCoupon.getDesc());
                wxCouponListBo.setDiscount(marketCoupon.getDiscount());
                wxCouponListBo.setName(marketCoupon.getName());
                wxCouponListBo.setMin(marketCoupon.getMin());
            } catch (NullPointerException ex) {
                ex.printStackTrace();
            }
            wxCouponListBo.setId(marketCouponUser.getId());

            if (marketCoupon.getStartTime() == null) {
                //当starttime为空时，说明开始时间为领取的时间，结束时间为领取时间加上有效期天数
                Date addTime = marketCoupon.getAddTime();
                wxCouponListBo.setStartTime(addTime);
                Calendar ca = Calendar.getInstance();
                ca.setTime(addTime);
                ca.add(Calendar.DATE, marketCoupon.getDays());
                Date endTime = ca.getTime();
                wxCouponListBo.setEndTime(endTime);
            } else {
                wxCouponListBo.setEndTime(marketCoupon.getEndTime());
                wxCouponListBo.setStartTime(marketCoupon.getStartTime());
            }
            boolean available = ifInDateOrOut(wxCouponListBo.getStartTime(), wxCouponListBo.getEndTime());
            wxCouponListBo.setAvailable(available);
            list.add(wxCouponListBo);
        }


        return new PageInfo<>(list);
    }
//    @Override
//    public PageInfo<WxCouponListBo> select(Short status, Integer page, Integer limit) {
//
//        Subject subject = SecurityUtils.getSubject();
//        // 获取 登录用户信息
//        MarketUser primaryPrincipal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
//        Integer id = primaryPrincipal.getId();
//
//        List<WxCouponListBo> list = new ArrayList<>();
//       // PageHelper.startPage(page, limit);
//
//        MarketCouponUserExample example1 = new MarketCouponUserExample();
//        MarketCouponUserExample.Criteria criteria1 = example1.createCriteria();
//        criteria1.andUserIdEqualTo(id);
//
//        List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(example1);
//        for (MarketCouponUser marketCouponUser : marketCouponUsers) {
//            WxCouponListBo wxCouponListBo = new WxCouponListBo();
//            Integer couponId = marketCouponUser.getCouponId();
//            MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(couponId);
//
//
//            wxCouponListBo.setCid(couponId);
//            try {
//                wxCouponListBo.setTag(marketCoupon.getTag());
//                wxCouponListBo.setDesc(marketCoupon.getDesc());
//                wxCouponListBo.setDiscount(marketCoupon.getDiscount());
//                wxCouponListBo.setName(marketCoupon.getName());
//                wxCouponListBo.setMin(marketCoupon.getMin());
//            }catch (NullPointerException ex){
//                ex.printStackTrace();
//            }
//            wxCouponListBo.setId(marketCouponUser.getId());
//
//            if (marketCoupon.getStartTime() == null) {
//                //当starttime为空时，说明开始时间为领取的时间，结束时间为领取时间加上有效期天数
//                Date addTime = marketCoupon.getAddTime();
//                wxCouponListBo.setStartTime(addTime);
//                Calendar ca = Calendar.getInstance();
//                ca.setTime(addTime);
//                ca.add(Calendar.DATE, marketCoupon.getDays());
//                Date endTime = ca.getTime();
//                wxCouponListBo.setEndTime(endTime);
//            } else {
//                wxCouponListBo.setEndTime(marketCoupon.getEndTime());
//                wxCouponListBo.setStartTime(marketCoupon.getStartTime());
//            }
//            boolean available = ifInDateOrOut(wxCouponListBo.getStartTime(), wxCouponListBo.getEndTime());
//
//            Short status1 = marketCouponUser.getStatus();
//            if (status1 == 1){
//                available = false;
//            }
//
//            if (!status.equals(status1)) {
//                continue;
//            }
//            wxCouponListBo.setAvailable(available);
//            list.add(wxCouponListBo);
//        }
//
//
//
//
//        PageHelper.startPage(page, limit);
//
//        return new PageInfo<>(list);
//    }

    /**
     * @description: 判断优惠券是否在有效期内
     * @author: yyr
     * @date: 2022/11/23 10:20
     * @param: [wxCouponListBo]
     * @return: java.lang.Boolean
     **/
    private Boolean ifInDateOrOut(Date startTime, Date endTime) {


        long now = System.currentTimeMillis();
        long startTime1 = startTime.getTime();
        long endTime1 = endTime.getTime();
        return now > startTime1 && now < endTime1;

    }


    @Override
    public PageInfo<WxCouponBo> selectCoupon(Integer page, Integer limit) {


        PageHelper.startPage(page, limit);

        List<MarketCoupon> marketCoupons1 = marketCouponMapper.selectCoupons2();


        List<WxCouponBo> wxCouponBos = new ArrayList<>();
        for (MarketCoupon marketCoupon : marketCoupons1) {

            WxCouponBo wxCouponBo = new WxCouponBo();
            wxCouponBo.setMin(marketCoupon.getMin());
            wxCouponBo.setName(marketCoupon.getName());
            wxCouponBo.setDiscount(marketCoupon.getDiscount());
            wxCouponBo.setDays(marketCoupon.getDays());
            wxCouponBo.setId(marketCoupon.getId());
            wxCouponBo.setTag(marketCoupon.getTag());
            wxCouponBo.setDesc(marketCoupon.getDesc());

            wxCouponBos.add(wxCouponBo);
        }
        return new PageInfo<>(wxCouponBos);
    }

    @Override
    public Integer insertUserByCid(Integer cid) {

        Subject subject = SecurityUtils.getSubject();
        // 获取 登录用户信息
        MarketUser primaryPrincipal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        Integer id = primaryPrincipal.getId();
        MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(cid);

        //首先判断优惠券是否可用
        int i = JudgeLimitAndTimes(marketCoupon, id);
        if (i == 1) {
            return 1;//"优惠券已发放完毕";
        } else if (i == 2) {
            return 2;//"优惠券已领取达上限";
        }


        MarketCouponUser marketCouponUser = new MarketCouponUser();
        setStarttimeAndEndTime(marketCoupon, marketCouponUser);
        if (ifInDateOrOut(marketCouponUser.getStartTime(), marketCouponUser.getEndTime())) {
            marketCoupon.setStatus((short) 0);
        } else {
            marketCoupon.setStatus((short) 2);
        }
        marketCouponMapper.updateByPrimaryKeySelective(marketCoupon);


        marketCouponUser.setUserId(id);
        marketCouponUser.setCouponId(cid);
        marketCouponUser.setUpdateTime(marketCoupon.getUpdateTime());
        marketCouponUser.setDeleted(marketCoupon.getDeleted());

        marketCouponUserMapper.insert(marketCouponUser);
        return 0;//"优惠券领取成功";
    }

    @Override
    public void insertByCode(String code) {
        Subject subject = SecurityUtils.getSubject();
        // 获取 登录用户信息
        MarketUser primaryPrincipal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        Integer id = primaryPrincipal.getId();


        MarketCouponExample example = new MarketCouponExample();
        MarketCouponExample.Criteria criteria = example.createCriteria();
        criteria.andCodeEqualTo(code);

        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(example);
        for (MarketCoupon marketCoupon : marketCoupons) {
            MarketCouponUser marketCouponUser = new MarketCouponUser();
            marketCouponUser.setUserId(id);
            marketCouponUser.setCouponId(marketCoupon.getId());
            setStarttimeAndEndTime(marketCoupon, marketCouponUser);
            marketCouponUser.setDeleted(marketCoupon.getDeleted());
            marketCouponUser.setUpdateTime(marketCoupon.getUpdateTime());
            // todo order_time 和 order_id 没有进行添加

            marketCouponUserMapper.insert(marketCouponUser);
        }

    }

    @Override
    public PageInfo<WxCouponListBo> selectCart(Integer cartId, Integer grouponRulesId) {
        PageHelper.startPage(1, 10);
        MarketCartExample example = new MarketCartExample();
        MarketCartExample.Criteria criteria = example.createCriteria();

        Subject subject = SecurityUtils.getSubject();
        // 获取 登录用户信息
        MarketUser primaryPrincipal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        Integer id = primaryPrincipal.getId();


        List<WxCouponListBo> wxCouponListBos = new ArrayList<>();
        BigDecimal num = new BigDecimal(0);
        if (cartId != 0) {
            MarketCart marketCart = marketCartMapper.selectByPrimaryKey(cartId);
            Short number = marketCart.getNumber();
            BigDecimal price = marketCart.getPrice();
            num = price.multiply(BigDecimal.valueOf(number));


        } else {
            MarketCartExample example1 = new MarketCartExample();
            MarketCartExample.Criteria criteria1 = example1.createCriteria();
            criteria1.andCheckedEqualTo(true);
            List<MarketCart> marketCarts = marketCartMapper.selectByExample(example1);


            for (MarketCart marketCart : marketCarts) {
                Short number = marketCart.getNumber();
                BigDecimal price = marketCart.getPrice();
                BigDecimal result3 = price.multiply(BigDecimal.valueOf(number));
                num = result3.add(num);
            }
        }
        MarketCouponExample example1 = new MarketCouponExample();
        MarketCouponExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andMinLessThanOrEqualTo(num);
        criteria1.andStatusEqualTo((short) 0);

        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(example1);


        for (MarketCoupon marketCoupon : marketCoupons) {

            Integer couponId = marketCoupon.getId();
            MarketCouponUserExample example3 = new MarketCouponUserExample();
            MarketCouponUserExample.Criteria criteria4 = example3.createCriteria();
            criteria4.andUserIdEqualTo(id);
            criteria4.andCouponIdEqualTo(couponId);
            criteria4.andStatusEqualTo((short) 0);

            List<MarketCouponUser> marketCouponUsers1 = marketCouponUserMapper.selectByExample(example3);
            if (marketCouponUsers1.size() == 0) {
                continue;
            }


            WxCouponListBo wxCouponListBo = new WxCouponListBo();
            wxCouponListBo.setMin(marketCoupon.getMin());
            wxCouponListBo.setName(marketCoupon.getName());

            wxCouponListBo.setTag(marketCoupon.getTag());
            wxCouponListBo.setCid(marketCoupon.getId());
            wxCouponListBo.setDesc(marketCoupon.getDesc());
            wxCouponListBo.setDiscount(marketCoupon.getDiscount());

            if (marketCoupon.getStartTime() == null) {
                //当starttime为空时，说明开始时间为领取的时间，结束时间为领取时间加上有效期天数
                Date addTime = marketCoupon.getAddTime();
                wxCouponListBo.setStartTime(addTime);
                Calendar ca = Calendar.getInstance();
                ca.setTime(addTime);
                ca.add(Calendar.DATE, 10);
                Date endTime = ca.getTime();
                wxCouponListBo.setEndTime(endTime);
            } else {
                wxCouponListBo.setEndTime(marketCoupon.getEndTime());
                wxCouponListBo.setStartTime(marketCoupon.getStartTime());
            }
            Boolean available = ifInDateOrOut(wxCouponListBo.getStartTime(), wxCouponListBo.getEndTime());


            wxCouponListBo.setAvailable(available);

            MarketCouponUserExample couponExample = new MarketCouponUserExample();
            MarketCouponUserExample.Criteria criteria3 = couponExample.createCriteria();
            criteria3.andCouponIdEqualTo(marketCoupon.getId());
            criteria3.andUserIdEqualTo(id);
            criteria3.andDeletedEqualTo(0);


            List<MarketCouponUser> marketCouponUsers = this.marketCouponUserMapper.selectByExample(couponExample);
            if (marketCouponUsers.size() == 0) {
                continue;
            }
            MarketCouponUser marketCouponUser = marketCouponUsers.get(0);
            wxCouponListBo.setId(marketCouponUser.getId());
            marketCouponUser.setDeleted(true);


            MarketCouponUserExample example2 = new MarketCouponUserExample();
            MarketCouponUserExample.Criteria criteria2 = example2.createCriteria();
            criteria2.andCouponIdEqualTo(marketCoupon.getId());

//            PageHelper.startPage(1,1);
//            List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(example2);
//
//            wxCouponListBo.setId(marketCouponUsers.get(0).getId());

            wxCouponListBos.add(wxCouponListBo);
        }
        return new PageInfo<>(wxCouponListBos);

    }

    /**
     * @description:
     * @author: yyr
     * @date: 2022/11/23 11:32
     * @param: [marketCoupon]
     * @return: boolean
     **/
    private int JudgeLimitAndTimes(MarketCoupon marketCoupon, Integer cid) {
        int limit = marketCoupon.getLimit();
        Integer couponId = marketCoupon.getId();
        Integer total = marketCoupon.getTotal();


        MarketCouponUserExample example = new MarketCouponUserExample();
        MarketCouponUserExample.Criteria criteria = example.createCriteria();

        if (total < limit) {
            criteria.andCouponIdEqualTo(couponId);
            int times = (int) marketCouponUserMapper.countByExample(example);

            if (total != 0) {
                if (times == total) {
                    return 1;//"优惠券已发放完毕";
                }
            } else {
                if (times == limit) {
                    return 2;//"优惠券已发放完毕";
                }

            }
        } else {

            criteria.andUserIdEqualTo(cid);
            criteria.andCouponIdEqualTo(couponId);

            int times = (int) marketCouponUserMapper.countByExample(example);
            if (limit == times) {
                return 2;
            }//"优惠券已领取达上限"
        }
        return 0;
    }

    private void setStarttimeAndEndTime(MarketCoupon marketCoupon, MarketCouponUser marketCouponUser) {
        Date addTime = marketCoupon.getAddTime();
        Date startTime = marketCoupon.getStartTime();

        marketCouponUser.setAddTime(addTime);
        if (startTime != null) {
            marketCouponUser.setStartTime(startTime);
            marketCouponUser.setEndTime(marketCoupon.getEndTime());
        } else {
            marketCouponUser.setStartTime(addTime);

            Short days = marketCoupon.getDays();
            Calendar ca = Calendar.getInstance();
            ca.setTime(addTime);
            ca.add(Calendar.DATE, days);
            Date endTime = ca.getTime();
            marketCouponUser.setEndTime(endTime);

        }

        Boolean judge = ifInDateOrOut(marketCouponUser.getStartTime(), marketCouponUser.getEndTime());
        if (judge) {
            marketCouponUser.setStatus((short) 0);
        } else {
            marketCouponUser.setStatus((short) 2);
        }

    }
    /*
        反射，解耦的主要技术
        注解，获取注解中的属性值
        wolidater 注解的不同带来了不同的信息
        注解和反射的结合，达到了简化的程度
        动态代理***
    */


}